﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace DATA_SERVER
{
    static class Program
    {
        public static MainForm mainfrm;
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]// 1 单线程套间
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();// 2 启用视觉样式
            Application.SetCompatibleTextRenderingDefault(false);// 3 设置兼容文本呈现默认值
            Application.AddMessageFilter(new MsgFilter());// 4 添加消息过滤器

            try
            {
                Process instance = RunningInstance();// 5 运行实例
                if (instance == null)
                {
                    Application.EnableVisualStyles();//=>2
                    Application.SetCompatibleTextRenderingDefault(false);//=>3
                    foreach (string argsstr in args)//检测启动参数 是否设为自动启动
                    {
                        if (argsstr == "-start")
                        {
                            Global.AutoStart = true;//全局变量
                        }
                    }
                    mainfrm = new MainForm();//开创一个主窗口 并运行
                    Application.Run(mainfrm);
                }
                else
                {
                    PostThreadMessage(instance.Threads[0].Id, 0x80FF, IntPtr.Zero, IntPtr.Zero);
                    //请求线程消息 :第一个线程ID  消息为0x80FF
                    //如果有实例 显示当前主界面
                }
            }
            catch { }
        }

        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostThreadMessage(int threadId, uint msg, IntPtr wParam, IntPtr lParam);

        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();//获取当前进程
            Process[] processes = Process.GetProcessesByName(current.ProcessName);//根据进程名称获取 进程集合
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    // 确保例程从EXE文件运行
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;
                    }
                }
            }
            return null;
        } 
    }

    class MsgFilter : IMessageFilter
    {
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x80FF)
            {
                Program.mainfrm.ShowWnd();
                return true;
            }
            return false;
        }
    }
}